package newNetty;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import config.MessageBo;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.net.URLDecoder;

import static config.Constants.mapUser;
import static config.Constants.userIdAddress;

@Component
@Configuration
public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketServerHandler.class);

    private WebSocketServerHandshaker handShaker;

    @Autowired
    public WebScoketHandler webScoketHandler;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg)
            throws Exception {

        logger.info("接收到请求：{}，信息体：{}",JSON.toJSONString(ctx),JSON.toJSONString(msg));

        /**
         * HTTP接入，WebSocket第一次连接使用HTTP连接,用于握手
         */
        if(msg instanceof FullHttpRequest){
            logger.info("处理http请求");
            handleHttpRequest(ctx, (FullHttpRequest)msg);
        }

        /**
         * Websocket 接入
         */
        else if (msg instanceof WebSocketFrame) {
            logger.info("接收到网络请求");
            handlerWebSocketFrame(ctx, (WebSocketFrame) msg);
        } else {
            logger.info("未识别的网络请求");
        }

    }



    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        logger.info("channelReadComplete : ctx{}", JSON.toJSONString(ctx));
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        System.out.println("exceptionCaught");
        ctx.close();
    }


    // 处理http请求
    private void handleHttpRequest(ChannelHandlerContext ctx,FullHttpRequest req){
        logger.info("处理socket请求");
        if (!req.getDecoderResult().isSuccess()
                || (!"websocket".equals(req.headers().get("Upgrade")))) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            logger.info("请求参数有误");
            return;
        }
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                "ws://localhost:2048/ws", null, false);
        handShaker = wsFactory.newHandshaker(req);
        if (handShaker == null) {
            logger.info("handShaker is null");
            WebSocketServerHandshakerFactory
                    .sendUnsupportedWebSocketVersionResponse(ctx.channel());
        } else {
            logger.info("handShaker : {}",JSON.toJSONString(handShaker));
            handShaker.handshake(ctx.channel(), req);
        }
    }

    private static void sendHttpResponse(ChannelHandlerContext ctx,
                                         FullHttpRequest req, DefaultFullHttpResponse res) {
        System.out.println("sendHttpResponse");
        // 返回应答给客户端
        if (res.getStatus().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(),
                    CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        // 如果是非Keep-Alive，关闭连接
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!isKeepAlive(req) || res.getStatus().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }



    private static boolean isKeepAlive(FullHttpRequest req) {
        System.out.println("isKeepAlive");
        return false;
    }

    private void handlerWebSocketFrame(ChannelHandlerContext ctx,
                                       WebSocketFrame frame) {
        logger.info("处理网络请求");
        logger.info("ctx:{},frame:{}",JSON.toJSONString(ctx),JSON.toJSONString(frame));

        /**
         * 判断是否关闭链路的指令
         */
        if (frame instanceof CloseWebSocketFrame) {
            String address = ctx.channel().remoteAddress().toString();
            handShaker.close(ctx.channel(),
                    (CloseWebSocketFrame) frame.retain());
            logger.info(JSON.toJSONString(mapUser));
            logger.info(JSON.toJSONString(userIdAddress));
            logger.info("mapUser remove {}",address);
            mapUser.remove(userIdAddress.get(address));
            logger.info("userIdAddress remove {}",address);
            userIdAddress.remove(address);
            logger.info(JSON.toJSONString(mapUser));
            logger.info(JSON.toJSONString(userIdAddress));
            logger.info("close web socket");
            return;
        }

        /**
         * 判断是否ping消息
         */
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(
                    new PongWebSocketFrame(frame.content().retain()));
            logger.info("ping");
            return;
        }

        /**
         * 本例程仅支持文本消息，不支持二进制消息
         */
        if (frame instanceof BinaryWebSocketFrame) {
            throw new UnsupportedOperationException(String.format(
                    "%s frame types not supported", frame.getClass().getName()));
        }
        if(frame instanceof TextWebSocketFrame){
            logger.info("处理Text信息");
            String messageStr = ((TextWebSocketFrame) frame).text();
            messageStr = URLDecoder.decode(messageStr);
            MessageBo messageBo = JSONObject.toJavaObject(JSONObject.parseObject(messageStr), MessageBo.class);
//            webScoketHandler.handler(ctx, messageBo);
            new WebScoketHandler().handler(ctx, messageBo);
        }

    }
}